<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Topic;
use App\Post;
use App\PostTopic;
class TopicController extends Controller
{
//    public function  show(){
//        //专题下的所有文章
//        $topic_id = \request('id');
//        $post_ids = PostTopic::where('topic_id',$topic_id)->get();
//        foreach ($post_ids as $my) {
//            echo $my->id.'<br/>';
//        };
//        $posts = Post::orderBy('created_at','desc')->whereIn('id',$post_ids->pluck('id'))->get();
//
//        //投稿
//        $uid = \Auth::id();
//        $myposts = Post::orderBy('created_at','desc')
//            ->where('user_id',$uid)
//            ->whereNotIn('id',$post_ids)
//            ->get();
//        foreach ($myposts as $my) {
//            echo $my->id.'<br/>';
//        };
//        dd($myposts);
//
//        return view('topic.show',compact('topics'));
//    }

    public function  show () {
        //带文章数的专题
        $id = \request('id');
        $topic = Topic::withCount('topicPosts')->find($id);

        $posts = $topic->posts()->orderBy('created_at','desc')->take(10)->get();

        $myposts = \App\Post::authorBy(\Auth::id())->topicNotBy($topic->id)->get();

        return view('topic/show', compact('topic', 'posts', 'myposts'));
    }
    public function submit()
    {
//        $topic = Topic::find(\request('id'));
//        $this->validate(request(),[
//            'post_ids' => 'array'
//        ]);
//
//        // 确认这些post都是属于当前用户的
//        $posts = Post::find(request('post_ids'));
//        foreach ($posts as $post) {
//            if ($post->user_id != \Auth::id()) {
//                return back()->withErrors(array('message' => '没有权限'));
//            }
//        }
//
//        $post_ids = request('post_ids');
//        $topic_id = $topic->id;
//        foreach ($post_ids as $post_id){
//           PostTopic::firstOrCreate(compact('topic_id', 'post_id'));
//        }

        $topic_id = \request('id');
        $post_ids = \request('post_ids');
        foreach ($post_ids as  $post_id){
            PostTopic::firstOrCreate(compact('topic_id','post_id'));
        }
        return back();
    }
}
